//
//  BLBiometric.m
//  CALayer
//
//  Created by Benz.L on 24/08/2018.
//  Copyright © 2018 BenzL. All rights reserved.
//

#import "BLBiometric.h"
#import <LocalAuthentication/LAContext.h>

@implementation BLBiometric

+ (BOOL)canBiometry:(LAPolicy)policy error:(NSError **)error {
    return [[LAContext new] canEvaluatePolicy:policy error:error];
}

+ (LABiometryType)biometryTypeWithPolicy:(LAPolicy)policy error:(NSError *__autoreleasing *)error {
    LABiometryType type = LABiometryNone;
    LAContext *ctx = LAContext.new;
    if ([ctx canEvaluatePolicy:policy error:error]) {
        type = ctx.biometryType;
    }
    return type;
}

+ (void)biometryPolicy:(LAPolicy)policy reason:(nonnull NSString *)reason fallbackTitle:(NSString *)fallbackTitle complete:(void(^)(NSError *error))complete {
    [self biometryPolicy:policy reason:reason fallbackTitle:fallbackTitle cancelTitle:nil complete:complete];
}

+ (void)biometryPolicy:(LAPolicy)policy reason:(nonnull NSString *)reason fallbackTitle:(NSString *)fallbackTitle cancelTitle:(NSString *)cancelTitle complete:(void(^)(NSError *error))complete {
    LAContext *context = [LAContext new];
    if (@available(iOS 11.0, *)) {
        context.localizedReason = reason;
    }
    if (@available(iOS 10.0, *)) {
        context.localizedCancelTitle = cancelTitle;
    }
    context.localizedFallbackTitle = fallbackTitle;
    
    NSError *error = nil;
    if (![self canBiometry:policy error:&error]) {
        if (complete) {
            dispatch_async(dispatch_get_main_queue(), ^{
                complete(error);
            });
        }
    }
    else {
        [context evaluatePolicy:policy localizedReason:reason reply:^(BOOL success, NSError * _Nullable error) {
            if (complete) {
                dispatch_async(dispatch_get_main_queue(), ^{
                    complete(error);
                });
            }
        }];
    }
}

@end
